﻿using Basic.FormDAL;
using Basic.FormModel.DB;
using Basic.FormModel.FormViewCol;
using Basic.FormRemoteModel.Form.Model;
using LinqKit;
using WeDonekRpc.Helper;

namespace Basic.FormCollect.lmpl
{
    internal class FormViewColCollect : IFormViewColCollect
    {
        private readonly IFormViewColDAL _ViewCol;

        public FormViewColCollect ( IFormViewColDAL viewCol )
        {
            this._ViewCol = viewCol;
        }
        public bool CheckIsExists ( long formId, string[] col )
        {
            return this._ViewCol.Count(c => c.FormId == formId && col.Contains(c.Alias)) == 2;
        }
        public long Add ( FormViewColAdd add )
        {
            return this._ViewCol.Add(add);
        }
        public DBFormViewCol Get ( long id )
        {
            return this._ViewCol.Get(id);
        }
        public Result Get<Result> ( long id ) where Result : class, new()
        {
            return this._ViewCol.Get<Result>(id);
        }
        public void Delete ( DBFormViewCol source )
        {
            this._ViewCol.Delete(source.Id);
        }
        public Result[] GetsByFormId<Result> ( long formId, FormGetParam param ) where Result : class, new()
        {
            ExpressionStarter<DBFormViewCol> where = PredicateBuilder.New<DBFormViewCol>(a => a.FormId == formId);
            if ( !param.TableId.IsNull() )
            {
                where = where.And(a => param.TableId.Contains(a.TableId));
            }
            if ( !param.FuncType.IsNull() )
            {
                where = where.And(a => param.FuncType.Contains(a.ColFuncType));
            }
            if ( !param.DataType.IsNull() )
            {
                where = where.And(a => param.DataType.Contains(a.DataType));
            }
            return this._ViewCol.Gets<Result>(where);
        }
        public Result[] Gets<Result> ( long[] ids ) where Result : class, new()
        {
            return this._ViewCol.Gets<Result>(ids);
        }
        public Result[] GetsByFormId<Result> ( long formId ) where Result : class, new()
        {
            return this._ViewCol.Gets<Result>(c => c.FormId == formId);
        }

        public bool Set ( DBFormViewCol sour, FormViewColSet data )
        {
            return this._ViewCol.Update(sour, data);
        }
        public Result[] Adds<Result> ( FormViewColAdd[] data ) where Result : class, new()
        {
            return this._ViewCol.Adds<Result>(data);
        }
        public Result[] Sync<Result> ( long formId, FormViewColAdd[] data ) where Result : class, new()
        {
            long[] ids = this._ViewCol.Gets(a => a.FormId == formId, a => a.Id);
            if ( ids.IsNull() )
            {
                return this._ViewCol.Adds<Result>(data);
            }
            return this._ViewCol.Sync<Result>(data, ids);
        }
    }
}
